import { useState } from 'react';
import { cn } from '@/lib/utils';
import { toast } from 'sonner';

export interface FileItem {
  id: string;
  name: string;
  size: string;
  modified: string;
  type: string;
  icon: string;
  data: string; // 存储文件的base64数据
}

interface FileListProps {
  files: FileItem[];
  onDelete: (id: string) => void;
}

export default function FileList({ files, onDelete }: FileListProps) {
  const [selectedFileId, setSelectedFileId] = useState<string | null>(null);
  
  const handleFileClick = (id: string, e: React.MouseEvent) => {
    e.stopPropagation();
    setSelectedFileId(prev => prev === id ? null : id);
  };
  
  const handleDownload = (file: FileItem, e: React.MouseEvent) => {
    e.stopPropagation();
    
    try {
      // 将base64数据转换为Blob
      const byteCharacters = atob(file.data);
      const byteNumbers = new Array(byteCharacters.length);
      for (let i = 0; i < byteCharacters.length; i++) {
        byteNumbers[i] = byteCharacters.charCodeAt(i);
      }
      const byteArray = new Uint8Array(byteNumbers);
      const blob = new Blob([byteArray], { type: 'application/octet-stream' });
      
      // 创建下载链接
      const url = URL.createObjectURL(blob);
      const a = document.createElement('a');
      a.href = url;
      a.download = file.name;
      document.body.appendChild(a);
      a.click();
      
      // 清理
      setTimeout(() => {
        document.body.removeChild(a);
        URL.revokeObjectURL(url);
      }, 0);
      
      toast.success(`已开始下载: ${file.name}`);
    } catch (error) {
      toast.error(`下载失败: ${file.name}`);
      console.error('Download error:', error);
    }
  };
  
  const handleDelete = (file: FileItem, e: React.MouseEvent) => {
    e.stopPropagation();
    if (window.confirm(`确定要删除 "${file.name}" 吗?`)) {
       toast(`已删除: ${file.name}`);
       onDelete(file.id);
     }
   };
  
  if (files.length === 0) {
    return (
      <div className="flex flex-col items-center justify-center h-64 text-gray-500">
        <i class="fa-solid fa-folder-open text-5xl mb-4"></i>
        <p>暂无文件</p>
        <p className="text-sm mt-1">上传文件以开始使用</p>
      </div>
    );
  }
  
  return (
    <div className="divide-y divide-gray-200 dark:divide-gray-700">
      {files.map((file) => (
        <div 
          key={file.id}
          className={cn(
            "flex items-center justify-between p-4 hover:bg-gray-50 dark:hover:bg-gray-700/50 transition-colors",
            selectedFileId === file.id ? "bg-blue-50 dark:bg-blue-900/10" : ""
          )}
          onClick={() => setSelectedFileId(file.id)}
        >
          <div className="flex items-center gap-4">
            
            {/* 文件图标 */}
            <div className={cn(
              "w-10 h-10 rounded flex items-center justify-center",
              file.type === 'folder' ? 'bg-blue-100 dark:bg-blue-900/30 text-blue-600 dark:text-blue-400' :
              file.type === 'document' ? 'bg-green-100 dark:bg-green-900/30 text-green-600 dark:text-green-400' :
              file.type === 'video' ? 'bg-purple-100 dark:bg-purple-900/30 text-purple-600 dark:text-purple-400' :
              'bg-gray-100 dark:bg-gray-700 text-gray-600 dark:text-gray-400'
            )}>
              <i class={`fa-solid ${file.icon} text-xl`}></i>
            </div>
            
            {/* 文件信息 */}
            <div>
              <h3 className="font-medium">{file.name}</h3>
              <p className="text-sm text-gray-500 dark:text-gray-400">{file.modified}</p>
            </div>
          </div>
          
          {/* 文件大小和操作 */}
          <div className="flex items-center gap-4">
            <span className="text-sm text-gray-500 dark:text-gray-400">{file.size}</span>
            
           <div className="flex gap-1 opacity-0 group-hover:opacity-100 transition-opacity">
               <button 
                 onClick={(e) => handleDownload(file, e)}
                 className="p-1.5 rounded hover:bg-gray-200 dark:hover:bg-gray-600"
                 title="下载"
               >
                 <i class="fa-solid fa-download text-sm"></i>
               </button>
               <button 
                 disabled
                 className="p-1.5 rounded hover:bg-gray-200 dark:hover:bg-gray-600 opacity-50 cursor-not-allowed"
                 title="分享功能暂未开放"
               >
                 <i class="fa-solid fa-share-alt text-sm"></i>
               </button>
               <button 
                 onClick={(e) => handleDelete(file, e)}
                 className="p-1.5 rounded hover:bg-gray-200 dark:hover:bg-gray-600"
                 title="删除"
               >
                 <i class="fa-solid fa-trash text-sm"></i>
               </button>
             </div>
          </div>
        </div>
      ))}
    </div>
  );
}